import { ref, } from "vue";
import * as Cesium from "cesium";
export const useCesiumClick = () => {
  const handler = ref();
  const isListening = ref(false);

  /**
   * 添加点击监听
   * @param {Cesium.Viewer} viewer - Cesium Viewer 实例
   * @param {(data: any) => void} callback - 点击回调函数
   * @param {boolean} [useTerrain=false] - 是否使用地形高度
   */
  const addClickListener = (viewer:Cesium.Viewer, callback:(data:any)=>void, useTerrain = false) => {
    // 确保 viewer 存在
    if (!viewer || !viewer.scene || !viewer.scene.canvas) {
      console.error("无法添加点击监听: Viewer 未准备好");
      return;
    }

    // 如果已存在监听，先移除
    if (handler.value) {
      removeClickListener();
    }

    // 创建新的事件处理器
    handler.value = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    isListening.value = true;

    handler.value.setInputAction(async (event:any) => {
      // 尝试获取点击位置的笛卡尔坐标
      let position = viewer.scene.pickPosition(event.position);
      let method = "pickPosition";

      // 如果 pickPosition 无效，则使用椭球体方法
      if (
        !position ||
        Cesium.Cartesian3.equals(position, Cesium.Cartesian3.ZERO)
      ) {
        position = viewer.camera.pickEllipsoid(
          event.position,
          viewer.scene.globe.ellipsoid
        ) as Cesium.Cartesian3;
        method = "pickEllipsoid";
      }

      if (position) {
        // 将笛卡尔坐标转换为地理坐标（弧度）
        const cartographic = Cesium.Cartographic.fromCartesian(position);
        let longitude = Cesium.Math.toDegrees(cartographic.longitude);
        let latitude = Cesium.Math.toDegrees(cartographic.latitude);
        let height = cartographic.height;

        // 如果启用地形高度
        if (useTerrain && viewer.terrainProvider) {
          try {
            const terrainPositions = await Cesium.sampleTerrainMostDetailed(
              viewer.terrainProvider,
              [Cesium.Cartographic.fromDegrees(longitude, latitude)]
            );
            height = terrainPositions[0].height;
            method = "terrainSample";
          } catch (e) {
            console.warn("地形采样失败，使用椭球高度", e);
          }
        }

        // 调用回调函数
        if (callback) {
          callback({
            position,
            longitude,
            latitude,
            height,
            method,
          });
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  };

  // 移除点击监听
  const removeClickListener = () => {
    if (handler.value && !handler.value.isDestroyed()) {
      handler.value.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      handler.value.destroy();
      handler.value = null;
    }
    isListening.value = false;
  };

  // 清理函数
  const destroy = () => {
    removeClickListener();
  };

  return {
    addClickListener,
    removeClickListener,
    isListening,
    destroy,
  };
};
